
package com.be.beadmin.project.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.basicData.dto.output.UserEx;
import com.be.beadmin.basicData.service.UserService;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.project.dto.input.BatchProduceSimpDto;
import com.be.beadmin.project.dto.input.BatchProductDto;
import com.be.beadmin.project.dto.input.ChangeDto;
import com.be.beadmin.project.dto.output.BatchProductEx;
import com.be.beadmin.project.entity.*;
import com.be.beadmin.project.mapper.BatchProductMapper;
import com.be.beadmin.project.mapper.BatchProductMapperEx;
import com.be.beadmin.project.repository.*;
import com.be.beadmin.project.service.BatchProductService;
import com.be.beadmin.project.service.ChangeService;
import com.be.beadmin.service.dto.output.DictDataEx;
import com.be.beadmin.service.entity.DictType;
import com.be.beadmin.service.entity.NotifyInfo;
import com.be.beadmin.service.impl.MinioService;
import com.be.beadmin.service.repository.DictTypeRepository;
import com.be.beadmin.service.repository.NotifyInfoRepository;
import com.be.beadmin.service.repository.NotifyTemplateInfoRepository;
import com.be.beadmin.service.service.DictDataService;
import com.be.beadmin.service.service.NotifyTemplateInfoService;
import com.be.beadmin.service.util.DateUtil;
import io.minio.errors.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.io.IOException;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @description 服务实现
* @author zjm
* @date 2023-02-13
**/
@Service
@RequiredArgsConstructor
public class BatchProductServiceImpl implements BatchProductService {

    @Autowired
    private BatchProductRepository batchProductRepository;
    @Autowired
    private  BatchProductMapper batchProductMapper;
    @Autowired
    private  BatchProductMapperEx batchProductExMapper;

    @Autowired
    private  BatchProductService batchProductService;

    @Autowired
    private ChangeService changeService;
    @Autowired
    private DictTypeRepository dictTypeRepository;
    @Autowired
    private DictDataService dictDataService;
    @Autowired
    private ProductTotalInfoRepository productTotalInfoRepository;
    @Autowired
    private InfoRepository infoRepository;
    @Autowired
    private TeamInfoRepository teamInfoRepository;
    @Autowired
    private BatchPlanRepository batchPlanRepository;
    @Autowired
    private MasterPlanRepository masterPlanRepository;
    @Autowired
    private MinioService minioService;
    @Autowired
    private UserService userService;

    @Autowired
    private NotifyTemplateInfoService notifyTemplateInfoService;

    @Autowired
    private NotifyTemplateInfoRepository notifyTemplateInfoRepository;

    @Autowired
    private NotifyInfoRepository notifyInfoRepository;


    private String reviewBucketName = "reviewfile";
    @Override
    public Page<BatchProductEx> getBatchProductByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<BatchProduct> page = batchProductRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(BatchProduct_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.notEqual(root.get(BatchProduct_.state), 0); // 必须
                    list.add(pre3);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(BatchProduct_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<BatchProductEx> page1 = page.map(batchProductExMapper::toEntity);
            return page1;

    }

    /**
     * 根据批次计划id获取所有的批次柜体
     *
     * @param batchPlanId
     * @return
     */
    @Override
    public List<BatchProduct> getBatchProductByBatchPlanId(String batchPlanId) {
        List<BatchProduct> products = batchProductRepository.findBatchProductByBatchPlanIdAndDelete(batchPlanId, 0);

        return products;
    }

    /**
     * 根据id获取柜体
     *
     * @param id
     * @return
     */
    @Override
    public BatchProduct getBatchProductById(String id) {
        return batchProductRepository.findBatchProductByIdAndDelete(id,0);
    }

    /**
     * 分页的查询接口BatchProduct
     *
     * @param pageEntity
     * @return
     */
    @Override
    public Page<BatchProduct> getBatchProductEntityByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<BatchProduct> page = batchProductRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(BatchProduct_.delete), 0); //过滤为0
                    list.add(pre2);

                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(BatchProduct_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        return page;
    }

    /**
     * 柜体设计的查询接口
     * @param pageEntity
     * @return
     */
    @Override
    public Page<BatchProduct> getBatchProductDesignByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<BatchProduct> page = batchProductRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(BatchProduct_.delete), 0); //过滤为0
                    list.add(pre2);
                    // 只显示设计中的柜体
                    Predicate pre3 = criteriaBuilder.notEqual(root.get(BatchProduct_.state), 0); //过滤不为
                    list.add(pre3);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(BatchProduct_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
//        Page<BatchProductEx> page1 = page.map(batchProductExMapper::toEntity);
        return page;

    }

    /**
     * 柜体设计已下发的查询接口
     * @param pageEntity
     * @return
     */
    @Override
    public Page<BatchProduct> getBatchProductDesignReleasedByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<BatchProduct> page = batchProductRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(BatchProduct_.delete), 0); //过滤为0
                    list.add(pre2);
                    // 只显示设计中的柜体
                    Predicate pre3 = criteriaBuilder.equal(root.get(BatchProduct_.state), 2); //过滤为0
                    list.add(pre3);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(BatchProduct_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
//        Page<BatchProductEx> page1 = page.map(batchProductExMapper::toEntity);
        return page;

    }

    /**
     * 删除指定项目下的所有柜体以及柜体的相关信息
     *
     * @param info
     */
    @Override
    public void deleteBatchProductAndRelationInfo(Info info) {
        // 柜体删除
        batchProductRepository.deleteBatchProductByInfoIdAndDelete(1, info.getId(), 0);
    }

    @Override
    public BatchProduct getWorkingHoursComparisonsByProductCode(String productCode) {
        BatchProduct batchProduct = batchProductRepository.findBatchProductByProductCodeAndDelete(productCode , 0);
        return batchProduct;
    }

    @Override
    public void addBatchProduct(BatchProductDto batchProductDto) {
            BatchProduct result = batchProductRepository.findBatchProductByIdAndDelete(batchProductDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("BatchProduct不存在,请重新查询");
            }
            BatchProduct batchProduct = batchProductMapper.toEntity(batchProductDto);
            batchProductRepository.save(batchProduct);
    }

    @Override
    public void updateBatchProduct(BatchProductDto batchProductDto) {
            BatchProduct batchProduct = batchProductRepository.findBatchProductById(batchProductDto.getId());
            batchProduct = batchProductMapper.toEntity(batchProductDto);
            batchProductRepository.save(batchProduct);
    }




    @Override
    public void delBatchProduct(String id) {
        BatchProduct batchProduct = batchProductRepository.findBatchProductById(id);
        batchProduct.setDelete(1);
        batchProductRepository.save(batchProduct);
    }


    /**
     * @return
     */
    @Override
    public List<String> getProduceType() {
        // 角色类型字典内容
//        DictTypeEx dictTypeEx = dictTypeService.getDictTypeByName("项目团队角色类型");
        DictType dictType = dictTypeRepository.findDictTypeByDictNameAndDelete("柜体类型",0);
        System.out.println("dictType:"+dictType);
//        System.out.println("dictTypeEx:"+dictTypeEx);
//        String roleTypeCode = dictTypeEx.getDictCode();
//        System.out.println("roleTypeCode:"+roleTypeCode);
        List<DictDataEx> produceType =  dictDataService.getDictDataExByDictTypeId(dictType);
        List<String> produceTypeList = new ArrayList<>();
        produceType.forEach(role-> produceTypeList.add(role.getKeyName()));
        return produceTypeList;
    }


    /**
     * @return
     */
    @Override
    public List<String> getErroType() {
        // 角色类型字典内容
//        DictTypeEx dictTypeEx = dictTypeService.getDictTypeByName("项目团队角色类型");
        DictType dictType = dictTypeRepository.findDictTypeByDictNameAndDelete("接线错误类型",0);
        System.out.println("dictType:"+dictType);
//        System.out.println("dictTypeEx:"+dictTypeEx);
//        String roleTypeCode = dictTypeEx.getDictCode();
//        System.out.println("roleTypeCode:"+roleTypeCode);
        List<DictDataEx> produceType =  dictDataService.getDictDataExByDictTypeId(dictType);
        List<String> produceTypeList = new ArrayList<>();
        produceType.forEach(role-> produceTypeList.add(role.getKeyName()));
        return produceTypeList;
    }


    /**
     * 根据批次计划id获取指定的批次柜体并分类
     * @param batchPlanId
     * @return
     */
    @Override
    public List<BatchProduceSimpDto> getProductByBatchPlan(String batchPlanId){
        BatchPlan batchPlan = batchPlanRepository.findBatchPlanByIdAndDelete(batchPlanId,0);
        MasterPlan masterPlan = masterPlanRepository.findMasterPlanByIdAndDelete(batchPlan.getMasterPlanId(),0);
        List<String> produceTypes = getProduceType();
        List<BatchProduceSimpDto> batchProduceSimpDtos = new ArrayList<>();
        for (int i = 0; i < produceTypes.size(); i++) {
            int count = batchProductRepository.countBatchProductByBatchPlanIdAndProductTypeAndIsStandardAndDelete(batchPlanId,produceTypes.get(i),1,0);
            if (count==0){
                continue;
            }
            ProductTotalInfo productTotalInfo  = productTotalInfoRepository.findProductTotalInfoByProductTypeAndIsStandardAndInfoIdAndDelete(produceTypes.get(i),1,masterPlan.getInfoId(),0);
            System.out.println("productTotalInfo:::"+productTotalInfo.getProductQty());

            BatchProduceSimpDto batchProduceSimpDto = new BatchProduceSimpDto();
            batchProduceSimpDto.setProductType(produceTypes.get(i));
            batchProduceSimpDto.setIsStandard(BigDecimal.valueOf(1));
            batchProduceSimpDto.setProductQty(count);
            batchProduceSimpDto.setMaxQty(productTotalInfo.getProductQty());
//            batchProduceSimpDto.setUnstandardName("-");
            batchProduceSimpDtos.add(batchProduceSimpDto);
        }

        List<String> unStandardNames = batchProductRepository.findUnstandardNameByIsStandardAndBatchPlanIdAndDelete(0,batchPlanId,0);
        for (int i = 0; i < produceTypes.size(); i++) {
            for (int j = 0; j < unStandardNames.size(); j++) {
                int count = batchProductRepository.countBatchProductByBatchPlanIdAndProductTypeAndUnstandardNameAndIsStandardAndDelete(batchPlanId,produceTypes.get(i),unStandardNames.get(j),0,0);
                if (count==0){
                    continue;
                }
                ProductTotalInfo productTotalInfo  = productTotalInfoRepository.findProductTotalInfoByProductTypeAndIsStandardAndInfoIdAndDelete(produceTypes.get(i),1,masterPlan.getInfoId(),0);
                BatchProduceSimpDto batchProduceSimpDto = new BatchProduceSimpDto();
                batchProduceSimpDto.setProductType(produceTypes.get(i));
                batchProduceSimpDto.setIsStandard(BigDecimal.valueOf(0));
                batchProduceSimpDto.setProductQty(count);
                batchProduceSimpDto.setMaxQty(productTotalInfo.getProductQty());
                batchProduceSimpDto.setUnstandardName(unStandardNames.get(j));
                batchProduceSimpDtos.add(batchProduceSimpDto);
            }

        }
        return batchProduceSimpDtos;
    }

    @Override
    public HashMap<String, String> getProductTypeAndCode() {
        // 角色类型字典内容
//        DictTypeEx dictTypeEx = dictTypeService.getDictTypeByName("项目团队角色类型");
        DictType dictType = dictTypeRepository.findDictTypeByDictName("柜体类型");
//        System.out.println("dictTypeEx:"+dictTypeEx);
//        String roleTypeCode = dictTypeEx.getDictCode();
//        System.out.println("roleTypeCode:"+roleTypeCode);
        List<DictDataEx> productTypeAndCode =  dictDataService.getDictDataExByDictTypeId(dictType);
        HashMap<String,String> productTypeAndCodeMap = new HashMap<>();
        productTypeAndCode.forEach(productType-> {
            productTypeAndCodeMap.put(productType.getKeyName(),productType.getKeyValue());
        });
        return productTypeAndCodeMap;
    }
    public void designReview(String batchProductId, int reviewState, String reviewMemo, MultipartFile multipartFile) throws InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        BatchProduct batchProductById = batchProductRepository.findBatchProductById(batchProductId);
        //设置审核备注
        batchProductById.setReviewMemo(reviewMemo);
        //设置审核人员
        //batchProductById.setReviewEditor(userId);
        //设置审核状态（审核结果）
        batchProductById.setReviewState(reviewState);
        //设置审核时间
        String now = DateUtil.getNow();
        batchProductById.setReviewTime(new Date());
        //设置审核附件
        if(!multipartFile.isEmpty()) {
            String originalFilename = multipartFile.getOriginalFilename();
            batchProductById.setReviewFileId(batchProductId + "-" + originalFilename);
            //上传审核附件
            minioService.uploadFile(reviewBucketName,batchProductId + "-" + originalFilename,multipartFile);
        }

        //更新数据库
        BatchProductDto batchProductDto = batchProductMapper.toDto(batchProductById);
        batchProductService.updateBatchProduct(batchProductDto);

    }

    public void commitDesignReview(String batchProductId) throws IOException, ParseException {
        BatchProduct batchProductById = batchProductRepository.findBatchProductById(batchProductId);

        //找到技术经理，并设置审核人
        String infoId = batchProductById.getInfoId();
        Info info = infoRepository.findInfoByIdAndDelete(infoId, 0);
        if(info==null){
            throw new BeadminException("项目不存在！");
        }
        TeamInfo teaminfo = teamInfoRepository.findTeamInfoByTeamIdAndCategoryAndDelete(info.getTeamId(), "技术经理", 0);
        if(teaminfo==null){
            throw new BeadminException("技术经理不存在！");
        }

        batchProductById.setReviewEditor(teaminfo.getUserName());
        //判断bom和图纸是否上传
        if(batchProductById.getBomId()==null){
            throw  new BeadminException("请先上传Bom！");
        }
//        if(batchProductById.getDrawingId()==null){
//            throw new BeadminException("请先上传图纸文件！");
//        }
        if (batchProductById.getIsWireFileUploaded() <= 0) throw new BeadminException("请上传箱柜接线表文件");
        if (batchProductById.getIsElectDrawingUploaded() <= 0) throw new BeadminException("请上传电气原理图文件");

//        if (batchProductById.getIsStdWorkHourUploaded() != 1){
//            throw new BeadminException("请先设置标准工时");
//        }
        //设为待审核
        batchProductById.setReviewState(1);
        //设置提交时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm");
        Date date = new Date();
        batchProductById.setSubmitTime(df.parse(df.format(date)));
        //更新数据库
        batchProductRepository.save(batchProductById);


        // 消息通知 工程师 -> 技术经理
        //-----------------------------------------------------------------------
        // 申请人 发送 工时补录 待办  审批人
        NotifyInfo notifyInfo =new NotifyInfo();
        notifyInfo.setModuleName("设计管理");
        notifyInfo.setFuncName("BOM/技术文件审批");
        notifyInfo.setNotifyDesc("非标柜体编码为["+batchProductById.getProductCode()+"]--BOM/技术文件待审批");
        notifyInfo.setNotifyType("待办");

        if (batchProductById.getEngineer() == null){
            notifyInfo.setSenderName("-");
        }else {
            notifyInfo.setSenderName(batchProductById.getEngineer());
        }
        notifyInfo.setSendTime(batchProductById.getSubmitTime());

        // 工时审核没有 用户id字段，用的用户名
        notifyInfo = notifyInfoRepository.save(notifyInfo);

        if (teaminfo.getUserName()!= null ) {
            notifyTemplateInfoService.sendNotify(notifyInfo, -2, teaminfo.getUserName(), teaminfo.getUserId());
        }

    }
    public void confirmDesignReview(String batchProductId, int reviewState, String reviewMemo, MultipartFile multipartFile) throws InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, ParseException {
        BatchProduct batchProductById = batchProductRepository.findBatchProductById(batchProductId);
        if(batchProductById.equals(null))
            throw new RuntimeException("未找到该柜体！");
        if(batchProductById.getReviewState().equals(0))
            throw new RuntimeException("请先确认上传该柜体！");
        else if(batchProductById.getReviewState().equals(2))
            throw new RuntimeException("已审核，请勿重复操作！");
        //设置审核备注
        batchProductById.setReviewMemo(reviewMemo);

        //设置审核人员
        //batchProductById.setReviewEditor(userEx.getName());
        //设置审核状态（审核结果）
        batchProductById.setReviewState(reviewState);
        //设置审核时间
        batchProductById.setReviewTime(DateUtil.transDateFormat(new Date()));
        //设置审核附件
        if(multipartFile!=null) {
            String originalFilename = multipartFile.getOriginalFilename();
            batchProductById.setReviewFileId(batchProductId + "-" + originalFilename);
            //上传审核附件
            minioService.uploadFile(reviewBucketName,batchProductId + "-" + originalFilename,multipartFile);
        }
        if(reviewState==2){

//            ChangeDto changeDto = new ChangeDto();
//
//            String infoId=batchProductById.getInfoId();
//            String batchPlanId = batchProductById.getBatchPlanId();
//            String batchPlanCode = batchProductById.getProductCode();
//
//            changeDto.setInfoId(infoId);
//            changeDto.setBatchPlanId(batchPlanId);
//            changeDto.setBatchPlanCode(batchPlanCode);
//            changeDto.setProductId(batchProductId);
//
//            Info info = infoRepository.findInfoByIdAndDelete(infoId,0);
//            changeDto.setProjectName(info.getProjectName());
//            changeDto.setContractCode(info.getContractCode());
//            changeDto.setContractName(info.getContractName());
//
//            MasterPlan masterPlan = masterPlanRepository.findMasterPlanByInfoIdAndDelete(infoId,0);
//            changeDto.setMasterPlanId(masterPlan.getId());
//            changeDto.setMasterPlanCode(masterPlan.getMasterPlanCode());
//
//            int drawingIsChange = batchProductById.getDrawingIsChange();
//            int bomIsChange = batchProductById.getBomIsChange();
//
//            changeDto.setIsStandard(batchProductById.getIsStandard());
//            changeDto.setProductCode(batchProductById.getProductCode());
//            //changeDto.setProductName(batchProductById.getProductName());
//            changeDto.setProductType(batchProductById.getProductType());
//
//            if(drawingIsChange>=0){
//                SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                changeDto.setChangeTime(sdf.format(System.currentTimeMillis()));
//                changeDto.setChangeType("图纸变更");
//                changeService.addChange(changeDto);
//            }
//
//
//            if(bomIsChange>=0){
//                SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                changeDto.setChangeTime(sdf.format(System.currentTimeMillis()));
//                changeDto.setChangeType("BOM变更");
//                changeService.addChange(changeDto);
//            }
            batchProductById.setDrawingIsChange(-1);
            batchProductById.setBomIsChange(-1);

        }
        batchProductRepository.save(batchProductById);
        // 消息通知： 驳回后技术经理->工程师
        // ---------------------------------------------
        if(reviewState == 3){
            NotifyInfo notifyInfo = new NotifyInfo();
            notifyInfo.setModuleName("设计管理");
            notifyInfo.setFuncName("BOM/技术文件审批");
            notifyInfo.setNotifyDesc("非柜体编码为["+batchProductById.getProductCode()+"]--BOM/技术文件审批被驳回");
            notifyInfo.setNotifyType("通知");

            Info info = infoRepository.findInfoByIdAndDelete(batchProductById.getInfoId(),0);
            TeamInfo teaminfo = teamInfoRepository.findTeamInfoByTeamIdAndCategoryAndDelete(info.getTeamId(), "技术经理", 0);

            if (teaminfo.getUserName()==null){
                notifyInfo.setSenderName("-");
            }else{
                notifyInfo.setSenderName(teaminfo.getUserName());
                notifyInfo.setSenderId(teaminfo.getUserId());
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm");
            Date date = new Date();
            notifyInfo.setSendTime(df.parse(df.format(date)));
            notifyInfo = notifyInfoRepository.save(notifyInfo);

            if (batchProductById.getEngineer() != null) {
                notifyTemplateInfoService.sendNotify(notifyInfo,-1,batchProductById.getEngineer(),null);
            }
        }
    }
    @Transactional
    public void batchConfirmDesignReview(List<String> batchProductId, int reviewState, String reviewMemo, MultipartFile multipartFile) throws InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, ParseException {
        for (String id:batchProductId) {
            confirmDesignReview(id,reviewState,reviewMemo,multipartFile);
        }
    }
    public void refuseDesignReview(String batchProductId){
        BatchProduct batchProductById = batchProductRepository.findBatchProductById(batchProductId);
        //设置状态
        batchProductById.setReviewState(0);

        batchProductRepository.save(batchProductById);
    }


    public void setBop(String batchProductId,String bopCode){
        BatchProduct b = batchProductRepository.findBatchProductById(batchProductId);
        b.setBopCode(bopCode);
        b.setIsDesignBop(1);
        batchProductRepository.save(b);
    }

    /**
     * 获取柜体待分配数量
     *
     * @param infoId
     */
    @Override
    public int getRestProductNums(String infoId) {

        int count =  batchProductRepository.countBatchProductsByInfoIdAndBatchPlanIdAndDelete(infoId,"-1",0);
        System.out.println("count"+count);
        return count;
    }


}